package com.shali.wechat.order.controller;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.shali.wechat.order.dto.CartDTO;
import com.shali.wechat.order.entity.ProductCategory;
import com.shali.wechat.order.entity.ProductInfo;
import com.shali.wechat.order.service.ProductCategoryService;
import com.shali.wechat.order.service.ProductService;
import com.shali.wechat.order.utils.ResultVOUtil;
import com.shali.wechat.order.vo.ProductInfoVO;
import com.shali.wechat.order.vo.ProductVO;
import com.shali.wechat.order.vo.ResultVO;

@RestController
@RequestMapping("/product")
public class ProductController {

	@Autowired
	private ProductService productService;
	
	@Autowired
	private ProductCategoryService productCategoryService;
	/**
	 * 1.查询所有在架的商品
	 * 2.获取类目type列表
	 * 3.查询类目
	 * 4.构造数据
	 */
	@SuppressWarnings("unchecked")
	@GetMapping("/list")
	public ResultVO<ProductVO> list() {
		//1.查询所有在架的商品
		List<ProductInfo> productList = productService.findUpAll();
		//2.获取类目type列表
		List<Integer> categoryTypeLists = productList.stream()
				.map(ProductInfo::getCategoryType)
				.collect(Collectors.toList());
		//3.从数据库查询类目
		List<ProductCategory> catagoryList = productCategoryService.findByCategoryTypeIn(categoryTypeLists);
		
		List<ProductVO> productVOList = new ArrayList<>();
		for(ProductCategory cata:catagoryList) {
			ProductVO productVO = new ProductVO();
			productVO.setCategoryName(cata.getCategoryName());
			productVO.setCategoryType(cata.getCategoryType());
			
			List<ProductInfoVO> productInfoList = new ArrayList<>();
			for(ProductInfo product:productList) {
				if(product.getCategoryType().equals(cata.getCategoryType())) {
					ProductInfoVO productInfo = new ProductInfoVO();
					BeanUtils.copyProperties(product, productInfo);
					productInfoList.add(productInfo);
				}
			}
			
			productVO.setProductInfoVOList(productInfoList);
			productVOList.add(productVO);
		}
		return ResultVOUtil.success(productVOList);
	}
	
	/**
	 * 根据IDs查询商品列表
	 * @param porductIdList
	 * @return
	 */
	@PostMapping("/listForOrder")
	public List<ProductInfo> getProductInfoList(@RequestBody List<String> ids){
		return productService.findByIds(ids);
	}
	
	@PostMapping("/decreaseStock")
	public void decreaseStock(@RequestBody List<CartDTO> cartDTOList){
		productService.decreaseStock(cartDTOList);
	}
}
